package com.book.store.service.store.endpoint;

import com.book.store.domain.store.entity.Book;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

@RestController
@RequestMapping("books")
public class BooksController {

    @GetMapping("")
    public List<Book> listBooks() {
        ArrayList<Book> books = getBooks();
        return books;
    }

    @GetMapping("books/{id}")
    public Book detail(@PathVariable String id, HttpServletResponse response) {
        Optional<Book> first = this.getBooks().stream()
                .filter(book -> book.getId().equals(id))
                .findFirst();
        if (first.isPresent()) {
            return first.get();
        } else {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
        return null;
    }

    private ArrayList<Book> getBooks() {
        ArrayList<Book> books = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            String id = String.valueOf(i);
            books.add(Book.builder()
                    .id(UUID.randomUUID().toString())
                    .name("book" + id)
                    .describe("awesome book " + id)
                    .createBy("system")
                    .createTime(new Date())
                    .build());
        }
        return books;
    }


}
